
import { CCFloat, CCInteger, Component, UITransform, _decorator } from 'cc';
import { ORDER_IN_LAYER_MAX } from './SortingDefine';
const { ccclass, property, type, disallowMultiple, requireComponent, executeInEditMode } = _decorator;

@ccclass('Custom Render/SortingGroup')
@requireComponent(UITransform)
@disallowMultiple(true)
@executeInEditMode(true)
export class SortingGroup extends Component {
    /**
     * 排序层
     */
    @property({ type: CCInteger })
    private _sortingLayer: number = 0;

    /**
     * 排序层
     */
    @property({ type: CCInteger })
    get sortingLayer() {
        return this._sortingLayer;
    }
    set sortingLayer(value: number) {
        this._sortingLayer = value;
        this.setSortingPriority();
    }

    /**
     * 排序值
     */
    @property({ type: CCFloat, min: 0, max: ORDER_IN_LAYER_MAX })
    private _orderInLayer: number = 0;

    /**
     * 排序值
     */
    @property({ type: CCFloat, min: 0, max: ORDER_IN_LAYER_MAX })
    get orderInLayer() {
        return this._orderInLayer;
    }
    set orderInLayer(value: number) {
        this._orderInLayer = value;
        this.setSortingPriority();
    }

    private _uiTransform: UITransform = null;

    onLoad() {
        this._uiTransform = this.getComponent(UITransform);
    }

    onEnable() {
        if (this._uiTransform) {
            this.setSortingPriority();
            this._uiTransform.sortingEnabled = true;
        }

    }

    onDisable() {
        if (this._uiTransform) {
            this._uiTransform.sortingPriority = 0;
            this._uiTransform.sortingEnabled = false;
        }

    }

    setSortingPriority() {
        if (this._uiTransform)
            this._uiTransform.sortingPriority = this._sortingLayer * ORDER_IN_LAYER_MAX + this._orderInLayer;
    }
}
